﻿using System.Linq;
using OpenRA.Graphics;
using OpenRA.Primitives;

namespace OpenRA.Mods.Common.Graphics
{
	[Desc("TA Special.")]
	public class CircleSelectionRenderable : IRenderable, IFinalizedRenderable
	{
		const int CircleSegments = 60;
		static readonly float2 TLOffset = new float2(-12, -6);
		static readonly float2 TROffset = new float2(12, -6);
		static readonly float2 TOffset = new float2(0, -13);
		static readonly float2[] Offsets =
		{
			-TROffset, -TLOffset, -TOffset,
			TROffset, -TOffset, -TLOffset,
			-TLOffset, TOffset, TROffset,
			TLOffset, TROffset, TOffset,
			-TROffset, TOffset, TLOffset,
			TLOffset, -TOffset, -TROffset
		};

		static readonly WVec[] FacingOffsets = Exts.MakeArray(CircleSegments, i => new WVec(0, -1024, 0).Rotate(WRot.FromFacing(i * 256 / CircleSegments)));
		readonly WPos centerPosition;
		readonly WDist radius;
		readonly Color color;
		readonly int width;
		/* readonly bool filled; */
		readonly int lineSegments = 2;
		int seglength;

		public CircleSelectionRenderable(Actor actor, WDist radius, Color color, int width)
		{
			centerPosition = actor.CenterPosition;
			this.radius = radius;
			this.color = color;
			this.width = width;
			seglength = CircleSegments / lineSegments;
		}

		public CircleSelectionRenderable(WPos pos, WDist radius, Color color, int width)
		{
			centerPosition = pos;
			this.radius = radius;
			this.color = color;
			this.width = width;
			seglength = CircleSegments / lineSegments;
		}

		public WPos Pos { get { return centerPosition; } }

		public int ZOffset { get { return 0; } }
		public bool IsDecoration { get { return true; } }

		public IRenderable WithZOffset(int newOffset) { return this; }
		public IRenderable OffsetBy(WVec vec) { return new CircleSelectionRenderable(centerPosition + vec, radius, color, width); }
		public IRenderable AsDecoration() { return this; }

		public IFinalizedRenderable PrepareRender(WorldRenderer wr) { return this; }

		public void Render(WorldRenderer wr)
		{
			var cr = Game.Renderer.RgbaColorRenderer;

			/*
			if (filled)
			{
				var offset = new WVec(radius.Length, radius.Length, 0);
				var tl = wr.Viewport.WorldToViewPx(wr.ScreenPosition(centerPosition - offset));
				var br = wr.Viewport.WorldToViewPx(wr.ScreenPosition(centerPosition + offset));

				cr.FillEllipse(tl, br, color);
			}
			else
			{
			*/

			var r = radius.Length;
			var a = wr.Viewport.WorldToViewPx(wr.ScreenPosition(centerPosition + r * FacingOffsets[CircleSegments - 1] / 1024));

			for (var i = 0; i < CircleSegments; i++)
			{
				var b = wr.Viewport.WorldToViewPx(wr.ScreenPosition(centerPosition + r * FacingOffsets[i] / 1024));
				if (i > CircleSegments / 6 && i < CircleSegments / 6 * 5)
					cr.DrawLine(a, b, width, color);
				a = b;
			}
		}

		public void RenderDebugGeometry(WorldRenderer wr) { }
		public Rectangle ScreenBounds(WorldRenderer wr) { return Rectangle.Empty; }
	}
}
